package com.kedacom.freedomLabel.view.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.kedacom.freedomLabel.R;

//public class OperationActivity extends AppCompatActivity {
//
//    @Override
//     protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_operation);
//    }
//}
//package com.scale.yaoscales;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;


//        import com.scale.yaoscales.base.AppConfig;
//        import com.scale.yaoscales.base.BaseActivity;
//        import com.scale.yaoscales.utils.NumFormatUtil;
import com.kedacom.freedomLabel.base.AppConfig;
import com.kedacom.freedomLabel.utils.NumFormatUtil;
import com.seray.scaleviewlib.dialog.ScaleTipDialog;
import com.seray.scaleviewlib.utils.LogUtils;
import com.seray.scaleviewlib.utils.ToastUtils;
import com.tscale.scalelib.jniscale.JNIScale;
import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class OperationActivity extends AppCompatActivity {

    private JNIScale mScale;
    private EditText et_calload, et_maxUnit;
    private TextView internelCount, weight;
    private Spinner mSpFdn, mSpBigFdn, mSpZeroRange,setUnit,setPoint, mSpRangeMode, mSpZeroTrack, mSpType;
    private Button demarcate, finishAll, maxUnitBtn, mZeroCodeBtn;
    private String[] arrDiv = {"1", "2", "5", "10", "20", "50", "100", "200", "500"};
    private String[] arrTrack;
    private String[] types = {"T-200", "SR-200"};
    private String[] rangeModes;
    private String[] zeroRangeTabs;
    private String[] unitSet = {"kg","g"};
    private String[] unitPoint = {"0","0.0","0.00","0.000","0.0000","0.00000","0.000000"};

    private OperationHandler mOperationHandler = new OperationHandler(new WeakReference
            <>(this));
    private boolean isDefaultFdn = true;
    private boolean isDefaultBigFdn = true;
    private boolean isDefaultTrack = true;
    private boolean isDefaultType = true;
    private boolean isDefaultRangeMode = true;
    private boolean isDefaultZeroRange = true;
    private boolean isDefaultUnit = true;
    private boolean isDefaultUnitPoint = true;
    private int step = 0;
    private int zeroStep = 0;
    private int zeroISN = 0;
    private float calload = 0.00f;
    //    private Runnable timerRun = () -> mOperationHandler.sendEmptyMessage(1);
    private Runnable timerRun = new Runnable() {
        @Override
        public void run() {
            mOperationHandler.sendEmptyMessage(1);
        }
    };

    /**
     * 执行定时任务固定数量线程池
     */
    private ScheduledExecutorService timerThreads = Executors.newScheduledThreadPool(1);

    private void _handleWeightChanged() {
        try{
            int count = mScale.getInternelCount();
            internelCount.setText(String.valueOf(count));
            weight.setText(mScale.getStringNet().trim());
        }catch (Exception e){
            LogUtils.d("显示出错了==="+e.toString());
        }

    }

//
//    @Override
//    protected int intiLayout() {
//        return R.layout.operationaltest;
//    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.operationaltest);
        initJNI();
        initView();
        initData();
        initListener();
        timer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timerThreads.shutdownNow();
        mOperationHandler.removeCallbacksAndMessages(null);
    }

    private void initJNI() {
        mScale = JNIScale.getScale();
        mScale.setMainUnit(1);
        mScale.setUnit(1);
//        mScale.setMainUnitDeci(5);
        mScale.setStabDelay(40);//秤的稳定时间150  --> 0.75s
    }


    public void initView() {
        internelCount = findViewById(R.id.internelCount);
        weight = findViewById(R.id.weight);
        demarcate = findViewById(R.id.calibration);
        et_calload = findViewById(R.id.et_calload);
        finishAll = findViewById(R.id.exitApp);
        mSpFdn = findViewById(R.id.setting_sp_fdn);
        mSpBigFdn = findViewById(R.id.setting_sp_bigFdn);
        mSpZeroTrack = findViewById(R.id.setting_sp_zerotrack);
        mSpRangeMode = findViewById(R.id.setting_sp_rangeMode);
        mSpType = findViewById(R.id.setting_sp_type);
        mSpZeroRange = findViewById(R.id.setting_sp_zeroRange);
        setPoint = findViewById(R.id.setting_point);
        setUnit = findViewById(R.id.setting_unit);
        maxUnitBtn = findViewById(R.id.maxuint);
        et_maxUnit = findViewById(R.id.et_maxuint);
        mZeroCodeBtn = findViewById(R.id.et_zero_btn);
    }

    public void initData() {

        arrTrack = getResources().getStringArray(R.array.division_values);
        rangeModes = getResources().getStringArray(R.array.range_mode);
        zeroRangeTabs = getResources().getStringArray(R.array.zero_mode);

        mSpFdn.setAdapter(new ArrayAdapter<>(this, android.R.layout
                .simple_spinner_dropdown_item, arrDiv));
        mSpBigFdn.setAdapter(new ArrayAdapter<>(this, android.R.layout
                .simple_spinner_dropdown_item, arrDiv));
        mSpZeroTrack.setAdapter(new ArrayAdapter<>(this, android.R.layout
                .select_dialog_item, arrTrack));
        mSpRangeMode.setAdapter(new ArrayAdapter<>(this, android.R.layout
                .select_dialog_item, rangeModes));
        mSpZeroRange.setAdapter(new ArrayAdapter<>(this, android.R.layout
                .select_dialog_item, zeroRangeTabs));
        setUnit.setAdapter(new ArrayAdapter<>(this, android.R.layout
                .select_dialog_item, unitSet));
        setPoint.setAdapter(new ArrayAdapter<>(this, android.R.layout
                .select_dialog_item, unitPoint));

        mSpType.setAdapter(new ArrayAdapter<>(this, android.R.layout
                .select_dialog_item, types));

        // 获取当前秤的最大量程 默认是0.0f

        if (String.valueOf(mScale.getMainUnitFull()) != null && !TextUtils.isEmpty(String.valueOf(mScale.getMainUnitFull()))) {
            float curMainUnit = mScale.getMainUnitFull();
            String unitStr = String.valueOf(curMainUnit);
            if (curMainUnit == 0.0f) {
                curMainUnit = AppConfig.isT200() ? 300.0f : 30.0f;
            }

            et_maxUnit.setText(unitStr);
        }


        // 获取当前分度值[1] 默认是0
        mSpFdn.setSelection(mScale.getFdnPtr());

        // 获取当前分度值[2] 默认是0
        mSpBigFdn.setSelection(mScale.getBigFdnPtr());

        // 获取当前量程模式 默认是单精度
        mSpRangeMode.setSelection(mScale.getRangeMode());

        // 获取当前开机自动置零和手动置零的范围 默认都是0.0%
        int curAutoPtr = mScale.getAutoZeroRangePtr();
        int curManualPtr = mScale.getManualZeroRangePtr();
        if (curAutoPtr == 0 || curAutoPtr != curManualPtr) {
//            boolean isSuccess =
            mScale.setAutoZeroRangePtr(curManualPtr);
//            if (!isSuccess) {
//                ToastUtils.showShort("设置开机自动置零范围失败");
//            }
        }
        mSpZeroRange.setSelection(curManualPtr);

        // 获取当前零点追踪范围索引 默认是0倍当前分度值
        mSpZeroTrack.setSelection(mScale.getZeroTrackPtr());

        // 设置默认选中的秤模式
        if (AppConfig.isT200()) {
            mSpType.setSelection(0);
        } else if (AppConfig.isSR200()) {
            mSpType.setSelection(1);
        }
    }

    private void initListener() {
        MyButtonListener btnListener = new MyButtonListener();
        weight.setOnClickListener(btnListener);
        demarcate.setOnClickListener(btnListener);
        finishAll.setOnClickListener(btnListener);
        maxUnitBtn.setOnClickListener(btnListener);
        mZeroCodeBtn.setOnClickListener(btnListener);
        mSpFdn.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultFdn) {
                    isDefaultFdn = false;
                    return;
                }
//                boolean isOk =
                mScale.setFdnPtr(position);
//                if (!isOk) {
//                    ToastUtils.showShort("分度值[1]设置失败");
//                } else {
//                    ToastUtils.showShort("分度值[1]设置成功");
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mSpBigFdn.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultBigFdn) {
                    isDefaultBigFdn = false;
                    return;
                }
//                boolean isOk =
                mScale.setBigFdnPtr(position);
//                if (!isOk) {
//                    ToastUtils.showShort("分度值[2]设置失败");
//                } else {
//                    ToastUtils.showShort("分度值[2]设置成功");
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mSpRangeMode.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultRangeMode) {
                    isDefaultRangeMode = false;
                    return;
                }
//                boolean isOk =
                mScale.setRangeMode(position);
//                if (!isOk) {
//                    ToastUtils.showShort("量程模式设置失败");
//                } else {
//                    ToastUtils.showShort("量程模式设置设置成功");
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mSpZeroRange.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultZeroRange) {
                    isDefaultZeroRange = false;
                    return;
                }
//                boolean isManualOk =
                mScale.setManualZeroRangePtr(position);
                // 增加设置自动归零范围
//                boolean isAutoOk =
                mScale.setAutoZeroRangePtr(position);
//                if (isManualOk && isAutoOk) {
//                    ToastUtils.showShort("置零范围设置成功");
//                } else if (!isManualOk) {
//                    ToastUtils.showShort("手动置零范围设置失败");
//                } else {
//                    ToastUtils.showShort("自动置零范围设置失败");
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mSpZeroTrack.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultTrack) {
                    isDefaultTrack = false;
                    return;
                }
//                boolean isOk =
                mScale.setZeroTrackPtr(position);
//                if (!isOk) {
//                    ToastUtils.showShort("追踪范围设置失败");
//                } else {
//                    ToastUtils.showShort("追踪范围设置成功");
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mSpType.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultType) {
                    isDefaultType = false;
                    return;
                }
                if (position == 0) {
                    AppConfig.SCALE_TYPE = AppConfig.ScaleType.T200;
                    mSpFdn.setSelection(4);
                    mSpRangeMode.setSelection(0);
                    et_maxUnit.setText(R.string.max_weight_1);
                } else if (position == 1) {
                    AppConfig.SCALE_TYPE = AppConfig.ScaleType.SR200;
                    mSpFdn.setSelection(1);
                    mSpBigFdn.setSelection(2);
                    mSpRangeMode.setSelection(1);
                    et_maxUnit.setText(R.string.max_weight_2);
                }
                AppConfig.saveScaleTypeToDb();
                showChangeScaleTypeDialog();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        setUnit.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultUnit) {
                    isDefaultUnit = false;
                    return;
                }

//                LogUtils.d("走这里了"+"=======");
//                boolean setMainUnitFull =  mScale.setMainUnitFull(0.3f); //设置主单位称重量程
//                boolean setMainUnitMidFull =mScale.setMainUnitMidFull(0.2f);//设置主单位半量程
                boolean isUnit  =  mScale.setUnit(position);
                mScale.setMainUnitDeci(4);

//                boolean ismainUnIT = mScale.setMainUnit(position);

                LogUtils.d("isUnit = "+isUnit);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        setPoint.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isDefaultUnitPoint) {
                    isDefaultUnitPoint = false;
                    return;
                }

                LogUtils.d("走这里了"+"======="+position);
                mScale.setMainUnitDeci(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void timer() {
        timerThreads.scheduleAtFixedRate(timerRun, 1500, 100, TimeUnit.MILLISECONDS);
    }

    private void showChangeScaleTypeDialog() {
        ScaleTipDialog tipDialog = new ScaleTipDialog(this);
        tipDialog.show();
        tipDialog.setMessage(R.string.dialog_msg_demarcate);
        tipDialog.setOnPositiveClickListener(R.string.manage_submit, null);
    }

    /**
     * 保存手动设置的最大量程
     */
    protected void setManualUnit() {
        String maxUnit = et_maxUnit.getText().toString();
        float inputMaxUnit;
        if (TextUtils.isEmpty(maxUnit)) {
            ToastUtils.showShort(R.string.oper_input_max_value);
        } else if (!NumFormatUtil.isNumeric(maxUnit)) {
            ToastUtils.showShort(R.string.oper_input_number);
            et_maxUnit.setText("");
        } else {
            inputMaxUnit = Float.parseFloat(maxUnit);// 输入的最大量程
            if (inputMaxUnit > 300&& mScale.getMainUnit()==0) {
                ToastUtils.showShort(R.string.oper_over_max);
            } else if (inputMaxUnit > 0) {
                mScale.setMainUnitFull(inputMaxUnit);// 设置主单位称重量程
                float midUnit = inputMaxUnit / 2;
                mScale.setMainUnitMidFull(midUnit);// 设置主单位半量程
                float curFullUnit = mScale.getMainUnitFull();
                if (curFullUnit == inputMaxUnit) {// 获取设置最大量程操作后的最大量程，可行
                    ToastUtils.showShort(R.string.oper_max_value_success);
                } else {
                    ToastUtils.showShort(R.string.oper_max_value_failed);
                }
            }
        }
    }

    private static class OperationHandler extends Handler {

        WeakReference<OperationActivity> mWeakReference;

        OperationHandler(WeakReference<OperationActivity> weakReference) {
            this.mWeakReference = weakReference;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            OperationActivity activity = mWeakReference.get();
            if (activity != null) {
                if (msg.what == 1) {
                    activity._handleWeightChanged();
                }
            }
        }
    }

    private class MyButtonListener implements OnClickListener {

        @Override
        public void onClick(View v) {
//            mMisc.beep();
            switch (v.getId()) {
                case R.id.calibration:
                    if (step == 0) {
                        ((Button) (v)).setText(R.string.oper_calibrate_zero);
                        step++;
                    } else if (step == 1) {
                        if (et_calload.getText().toString().isEmpty()) {
                            step = 0;
                            ((Button) (v)).setText(R.string.oper_calibrate);
                            break;
                        }
                        calload = Float.valueOf(et_calload.getText().toString().trim());
                        zeroISN = mScale.getInternelCount();

//                        ((Button) (v)).setText(String.format("%s%skg", getString(R.string.oper_calibrate_weight), calload));
                        try{
//                            mScale.setMainUnit(1);
//                            mScale.setUnit(1);

                            LogUtils.d(mScale.getMainUnit()+"=======");
                            if(mScale.getMainUnit()==1){
                                ((Button) (v)).setText(String.format("%s%sg", getString(R.string.oper_calibrate_weight), calload));
                            }else {
                                ((Button) (v)).setText(String.format("%s%skg", getString(R.string.oper_calibrate_weight), calload));
                            }
                        }catch (Exception e){
                            LogUtils.d(mScale.getMainUnit()+"=======");
                        }

                        step++;
                    } else if (step == 2) {
                        try{
                            int count = mScale.getInternelCount();
                            boolean cali = mScale.saveNormalCalibration(zeroISN, count, calload);
                            if (cali) {
                                ToastUtils.showShort(R.string.oper_calibrate_success);
                            } else {
                                ToastUtils.showShort(R.string.oper_calibrate_failed);
                            }
                            ((Button) (v)).setText(R.string.oper_calibrate);
                        }catch (Exception e){
                            LogUtils.d(mScale.getMainUnit()+"标定完成=======");
                        }

                        step = 0;
                    }
                    break;
                case R.id.exitApp:
                    finish();
                    break;
                case R.id.maxuint:
                    setManualUnit();
                    break;
                case R.id.et_zero_btn:
                    TextView zeroTv = findViewById(R.id.et_zero);
                    if (zeroStep == 0) {
                        mZeroCodeBtn.setText(R.string.oper_save_zero);
                        int zeroCode = mScale.getInternelCount();
                        zeroTv.setText(String.valueOf(zeroCode));
                        zeroStep++;
                    } else if (zeroStep == 1) {
                        mZeroCodeBtn.setText(R.string.oper_reset);
                        zeroStep = 0;
                    }
                    break;
            }
        }
    }
}
